<?php
namespace Home\Controller;
header('content-type:text/html;charset=utf-8');
use Think\Controller;
class CartController extends Controller {
    public function index(){

        //实例化cart表
        $goodscart=M('Cart');
        $goodscart->create();

        $mycart=$goodscart->where('userid='.$_SESSION['id'])->select();

        $this->assign('mycart',$mycart);

        $this->display();

    }

    //删除单个商品
    public function del(){
    	$cart=M('Cart');
    	$goodsid=I('get.goodsid');

    	$c=$cart->where('goodsid='.$goodsid)->delete();

    	if($c){
    		$this->success('删除成功',''.__CONTROLLER__.'/index/goodsNum/1');
    	}
    }

    //清空购物车
    public function delall(){
        $cart=M('Cart');
        $userid=I('get.userid');

        $c=$cart->where('userid='.$userid)->delete();

        if($c){
            $this->success('清除购物车成功',''.__CONTROLLER__.'/index/goodsNum/1');
        }
    }

    public function ajax()
    {
        $goodsid=I('post.id');//商品id
        $num=I('post.m');//商品购买数量
        //实例化商品表
        $good=M('Goods');
        $goods=$good->where('goodsid='.$goodsid)->find();
        //定义数组存放数据
        $data = array();
        $data['goodsid']=$goodsid;
        $data['number']=$num;
        $data['goodspic']=$goods['goodspic'];
        $data['goodsname']=$goods['goodsname'];
        $data['goodsprice']=$goods['price'];
        $data['xiaoji']=$data['number'] * $data['goodsprice'];
        $userid=$_SESSION['id'];
        $data['userid']=$userid;
        //实例化cart表
        $goodscart=M('Cart');
        $goodscart->create();
        //查询该商品是否在购物车内
        $cart=$goodscart->where('goodsid='.$goodsid.' AND userid='.$userid)->find();
        if($cart){
            //重新定义商品的数量和小计
            $data['number'] = ($num+$cart['number']);
            $data['xiaoji']=$data['number'] * $data['goodsprice'];
            //修改购物的数据
            $id = $goodscart->where('goodsid='.$goodsid.' AND userid='.$userid)->data($data)->save();

        }else{
            //将商品添加进购物车
            $id = $goodscart->data($data)->add();
        }
        //将数据通过json格式传递回页面
        exit(json_encode($id));
    }


}